﻿using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;

namespace Mal.Balades.AdminBusiness.DataModel
{
    public partial class FeedItem
    {
        #region Fields

        #endregion

        #region Construction / Destruction
        public FeedItem(SyndicationItem item)
            : this()
        {
            this.Title = item.Title.Text;
            if (item.Summary != null)
            {
                this.Summary = item.Summary.Text;
            }
            else
            {
                if (item.Content != null && item.Content is TextSyndicationContent)
                {
                    this.Summary = ((TextSyndicationContent)item.Content).Text;
                }
            }

            if (item.Links.Count == 1)
            {
                this.Url = item.Links[0].Uri.ToString();
            }
            else
            {
                foreach (SyndicationLink link in item.Links)
                {
                    if (link.MediaType == "text/html")
                        this.Url = link.Uri.ToString();
                }
            }

            if (!this.Url.StartsWith("http"))
            {
                if (item.Id.StartsWith("http"))
                {
                    this.Url = item.Id;
                }
                else
                {
                    this.Url = null;
                }
            }

            this.PublishedDate = item.PublishDate.DateTime;
        }
        #endregion

        #region enum, struct, class

        #endregion

        #region Properties

        #endregion

        #region Methods
        public static List<FeedItem> Convert(List<SyndicationItem> items)
        {
            return Convert(items, items.Count);
        }

        public static List<FeedItem> Convert(List<SyndicationItem> items, int numberOfItems)
        {
            List<FeedItem> feedItems = new List<FeedItem>();

            for (int i = 0; i < Math.Min(numberOfItems, items.Count); i++)
            {
                FeedItem feedItem = new FeedItem(items[i]);

                if(!string.IsNullOrEmpty(feedItem.Url))
                {
                    feedItems.Add(new FeedItem(items[i]));
                }
            }

            return feedItems;
        }
        #endregion

        #region Events

        #endregion
    }
}
